package com.wgts.wgts.tools;


import android.util.Log;

import com.wgts.wgts.netmodle.AppOkHttpClient;
import com.wgts.wgts.netmodle.NetWorkFactory;
import com.wgts.wgts.netmodle.TransformUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;

/**
 * 1.调用方法，判断线程池中是否存在线程
 * 2.存在则调用线程，不存在则新建线程
 * 3.任务销毁时候先遍历观察者是否还存在，若不存在销毁线程
 */
public class CountDownTime {

    private List<CountDownTimerListener> arrayList;

    private static final int ONECE_TIME = 1000;


    private ScheduledExecutorService scheduled;

    private CountDownTime(){
        arrayList = Collections.synchronizedList(new ArrayList<CountDownTimerListener>());
    }


    private static class SingletonHolder{
        private static final CountDownTime _INSTANCE = new CountDownTime();
    }

    public static CountDownTime getInstance(){
        return SingletonHolder._INSTANCE;
    }

    public void addCountDownTimerListener(CountDownTimerListener countDownTimerListener){
        if(scheduled == null || scheduled.isShutdown()){
            scheduledExecutorService();
        }
        arrayList.add(countDownTimerListener);

    }

    public void removeCountDownTimerListener(CountDownTimerListener countDownTimerListener){
        if(countDownTimerListener == null){
            return;
        }
        arrayList.remove(countDownTimerListener);
        if(arrayList.size() == 0){
            try {
                if(scheduled != null){
                    scheduled.shutdownNow();
                }
            }catch (Exception e){
                Log.d("", "");
            }finally {
                scheduled = null;
            }
        }
    }


    private void scheduledExecutorService() {
        //初始化一个线程池大小为 1 的 ScheduledExecutorService
        scheduled = new ScheduledThreadPoolExecutor(1);

        scheduled.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
               if(arrayList != null && arrayList.size() > 0){
                   for(CountDownTimerListener countDownTimerListener : arrayList){
                       try{
                           countDownTimerListener.countDownTimerListener();
                       }catch (Exception e){
                           Log.d("=====CountDownTime=====", e.getMessage());
                       }
                   }
               }
            }
        }, 0, ONECE_TIME, TimeUnit.MILLISECONDS);
    }



    public void startTime() {
        Observable.interval(0, 1, TimeUnit.SECONDS).compose(TransformUtils.<Long>defaultSchedulers())
                .subscribe();
    }







}
